package cn.stronglink.assetmanage.utils.dao;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.InventoryDao;
import cn.stronglink.assetmanage.dao.InventoryDetailDao;
import cn.stronglink.assetmanage.entity.Inventory;
import cn.stronglink.assetmanage.entity.InventoryDetail;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.utils.Constants;

/**
 * 盘点数据库交互
 */
public abstract class InventoryDataUtil {

    /**
     * 获取资产列表
     */
    public static List<SearchAsset> getSearchAsset() {
        List<SearchAsset> searchAssetList = DaoManager
                .getDaoSession(MyApplication.APP_CONTEXT).getSearchAssetDao().queryBuilder().distinct()
                .list();

        if (searchAssetList != null || searchAssetList.size() != 0) {
            return searchAssetList;
        }
        return null;
    }


    /**
     * 获取盘点单
     */
    public static List<Inventory> getInventory() {
        List<Inventory> inventoryList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getInventoryDao().queryBuilder().distinct()
                .orderDesc(InventoryDao.Properties.Id_)
                .orderDesc(InventoryDao.Properties.ExecuteTime).list();
        if (inventoryList != null || inventoryList.size() != 0) {
            return inventoryList;
        }
        return null;
    }

    /**
     * 通过inventoryId获取盘点单
     *
     * @param inventoryId
     * @return
     */
    public static Inventory getInventoryByOrderNo(String inventoryId) {
        List<Inventory> inventoryList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getInventoryDao().queryBuilder().distinct()
                .where(InventoryDao.Properties.Id_.eq(inventoryId)).list();
        Inventory inventory = new Inventory();
        if (inventoryList != null || inventoryList.size() > 0) {
            inventory = inventoryList.get(0);
        }

        if (inventory != null) {
            return inventory;
        }
        return null;

    }

    /**
     * 保存盘点单到数据库
     *
     * @param resultJson
     */
    public static void saveInventoryData(String resultJson) {
        Result<List<Inventory>> inventoryResult = null;
        Gson gson = new Gson();
        inventoryResult = gson.fromJson(resultJson, new TypeToken<Result<List<Inventory>>>() {
        }.getType());
        if (inventoryResult != null && inventoryResult.getHttpCode() == HttpURLConnection.HTTP_OK) {
            if (inventoryResult.getData() != null) {
                List<Inventory> inventoryList = inventoryResult.getData();

                if (inventoryList != null && inventoryList.size() > 0) {
                    //从服务器获取盘点数据
                    for (Inventory inventory : inventoryList) {
                        // 如果盘点单存在，就不添加
                        Inventory tempInventory = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDao().queryBuilder().where(
                                InventoryDao.Properties.Id_.eq(inventory.getId_())
                        ).unique();
                        if (tempInventory != null) {
                            continue;
                        }

                        inventory.setOrderType(Constants.STATUS_TWO);

                        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDao().insert(inventory);
                        // 获取详情
                        // 获取详情
                        List<SearchAsset> searchAssetList = PatrolDataUtil.getSearchAssetByBoomName(inventory.getRoomName());
                        InventoryDataUtil.saveInventoryDetailData(inventory, searchAssetList);
                    }
                }
            }
        }
    }

    /**
     * 获取地点列表
     */
    public static List<Room> getAreaList() {
        List<Room> roomList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getRoomDao().loadAll();

        if (roomList != null || roomList.size() != 0) {
            return roomList;
        }
        return null;
    }

    /**
     * 创建盘盈资产实例
     *
     * @param inventoryOrderId
     * @param goodsRfid
     * @return
     */
    public static InventoryDetail createInventoryProfitGoods(String inventoryOrderId, String goodsRfid) {
        InventoryDetail goods = new InventoryDetail();
        goods.setOrderNo(inventoryOrderId);
        goods.setRfidNo(goodsRfid);
        goods.setStatus(Constants.STATUS_FIVE);
        return goods;
    }

    /**
     * 保存盘点单到本地
     */
    public static boolean saveInventory(Inventory inventory) {
        try {
            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDao().update(inventory);
            saveInventoryDetailList(inventory.getDetailList(), inventory);
            saveInventoryDetailList(inventory.getMoreOutList(), inventory);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    public static void saveInventoryDetailList(List<InventoryDetail> inventoryDetailList, Inventory inventory) {
        if (inventoryDetailList != null && inventoryDetailList.size() > 0) {
            for (InventoryDetail inventoryDetail : inventoryDetailList) {
                inventoryDetail.setOrderNo(inventory.getId_());
                DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDetailDao().insertOrReplace(inventoryDetail);
            }

        }
    }


    public static List<InventoryDetail> getInventoryDetailListByOrderId(String inventoryId) {
        List<InventoryDetail> inventoryDetailList = new ArrayList<>();
        inventoryDetailList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDetailDao()
                .queryBuilder().where(InventoryDetailDao.Properties.OrderNo.eq(inventoryId))
                .list();
        return inventoryDetailList;
    }

    public static void saveInventoryDetailData(Inventory inventory, List<SearchAsset> searchAssetList) {
        if (searchAssetList != null && searchAssetList.size() > 0) {
            for (SearchAsset searchAsset : searchAssetList) {
                InventoryDetail inventoryDetail = new InventoryDetail();
                inventoryDetail.setOrderNo(inventory.getId_());
                saveSearchDataToInventoryDetail(inventoryDetail, searchAsset, true);
            }
        }
    }

    /**
     * 与服务器盘点单中资产数据查询条件保持一致，rackId为空的，
     * type.is_rack = 0
     * AND a.status_ in (1,2,6)
     *
     * @param inventoryDetail
     * @param searchAsset
     * @param isInit
     */
    public static void saveSearchDataToInventoryDetail(InventoryDetail inventoryDetail, SearchAsset searchAsset, boolean isInit) {
        if (searchAsset.getStatus() == 1 || searchAsset.getStatus() == 2 ||
                searchAsset.getStatus() == 6 || !"".equals(searchAsset.getRackId_())) {
            inventoryDetail.setOrderNo(inventoryDetail.getOrderNo());
            inventoryDetail.setAssetName(searchAsset.getAssetName());
            inventoryDetail.setAssetNo(searchAsset.getAssetNo());
            inventoryDetail.setBrandId(searchAsset.getBrandId());
            inventoryDetail.setBrandId_(searchAsset.getBrandId_());
            inventoryDetail.setBrandName(searchAsset.getBrandName());
            inventoryDetail.setBuyTime(searchAsset.getBuyTime());
            inventoryDetail.setDatacenterId(searchAsset.getDatacenterId());
            inventoryDetail.setDatacenterId_(searchAsset.getDatacenterId_());
            inventoryDetail.setEndUser(searchAsset.getEndUser());
            inventoryDetail.setId(searchAsset.getId());
            inventoryDetail.setId_(searchAsset.getId_());
            inventoryDetail.setManageBranchId(searchAsset.getManageBranchId());
            inventoryDetail.setManageBranchId_(searchAsset.getManageBranchId_());
            inventoryDetail.setModelId(searchAsset.getModelId());
            inventoryDetail.setModelId_(searchAsset.getModelId_());
            inventoryDetail.setModelName(searchAsset.getModelName());
            inventoryDetail.setPrice(searchAsset.getPrice());
            inventoryDetail.setRackId(searchAsset.getRackId());
            inventoryDetail.setRackId_(searchAsset.getRackId_());
            inventoryDetail.setRackName(searchAsset.getRackName());
            inventoryDetail.setRfidNo(searchAsset.getRfidNo());
            inventoryDetail.setRoomId(searchAsset.getRoomId());
            inventoryDetail.setRoomId_(searchAsset.getRoomId_());
            inventoryDetail.setRoomName(searchAsset.getRoomName());
            inventoryDetail.setSerialNo(searchAsset.getSerialNo());
            //未盘点
            if (isInit) {
                inventoryDetail.setStatus(Constants.STATUS_ONE);
            } else {
                inventoryDetail.setStatus(inventoryDetail.getStatus());
            }
            inventoryDetail.setTypeId(searchAsset.getTypeId());
            inventoryDetail.setTypeId_(searchAsset.getTypeId_());
            inventoryDetail.setTypeName(searchAsset.getTypeName());
            inventoryDetail.setUseBranchId(searchAsset.getManageBranchId());
            inventoryDetail.setUseBranchId_(searchAsset.getManageBranchId_());
            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).
                    getInventoryDetailDao().insertOrReplace(inventoryDetail);
        }
    }

    public static InventoryDetail getInventoryDetailListByOrderId_(String id_) {
        List<InventoryDetail> inventoryDetailList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT)
                .getInventoryDetailDao().queryBuilder().where(InventoryDetailDao.Properties.Id_.eq(id_)).distinct()
                .list();
        if (inventoryDetailList != null && inventoryDetailList.size() > 0) {
            return inventoryDetailList.get(0);
        }
        return null;
    }

    public static void deleteInventory(Inventory inventory) {
        if (inventory != null) {
            List<InventoryDetail> inventoryDetailList = getInventoryDetailListByOrderId(inventory.getId_());
            if (inventoryDetailList != null) {
                for (InventoryDetail inventoryDetail : inventoryDetailList) {
                    DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDetailDao().delete(inventoryDetail);
                }
            }
            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDao().delete(inventory);
        }
    }

    public static void saveInventoryDetail(InventoryDetail inventoryDetail) {
        if (inventoryDetail!=null){
            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDetailDao().insertOrReplace(inventoryDetail);
        }
    }
}
